package net.togogo.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.net.URLEncoder;

@Controller
public class FileUploadController {

    //获取文件上传页面
    //@RequestMapping(value = "/getfileupload",method = RequestMethod.GET)
    @GetMapping("/getfileupload")
    public String getfileupload(){
        return "fileupload";
    }

    //文件上传    oss   nginx
    //@RequestMapping(value = "/uploadfile",method = RequestMethod.POST)
    @PostMapping("/uploadfile")
    public String uploadFile(HttpServletRequest request, HttpSession session, String username,
                             @RequestParam("uploadfile")MultipartFile uploadfiles) throws IOException {
        //获取上传的作者
        System.out.println("作者 = " + request.getParameter("username"));
        //获取上传的文件名
        String filename = uploadfiles.getOriginalFilename();
        System.out.println("获取到的文件名是=" + filename);
        //获取上传文件目录/路径
        String realPath = session.getServletContext().getRealPath("/img");
        //若路径合法/存在 就创建新文件
        File file = new File(realPath,filename);
        //判断目标文件路径是否存在
        if (!file.getParentFile().exists()){
            file.getParentFile().mkdir();
            System.out.println("file = " + file);
        }
        uploadfiles.transferTo(file);
        return "success";
    }

    //文件下载
    @RequestMapping("/download")
    public void download(String filePath, HttpServletRequest request, HttpServletResponse response) throws IOException {
        //获取目标文件的路径
        String realPath = request.getSession().getServletContext().getRealPath(filePath);
        System.out.println("获取到的目标文件路径是 = " + realPath);
        //设置下载文件的文件名
        String newFileNmae = "xinwenjian.jpg";
        //设置下载字符编码 UTF-8
        response.setHeader("content-disposition", "attachment; filename=" + URLEncoder.encode(newFileNmae, "utf-8"));
        //获取下载的资源
        FileInputStream fs = new FileInputStream(realPath);
        int len = 0;
        byte[] buf = new byte[1024];
        while ((len=fs.read(buf))!=-1){
            response.getOutputStream().write(buf,0,len);
        }
    }
}
